/*
 * @Author: wuzhen
 * @Date: 2020-01-18 09:04:31
 * @LastEditors: wuzhen
 * @LastEditTime: 2020-04-20 17:17:24
 * @Description: 消息处理
 */
/* eslint-disable */
import { Message } from "view-design";
export default {
  data() {
    return {};
  },
  methods: {
    // 服务器消息类型
    systemMsg(data) {
      switch (data.resultType) {
        case 10: // 消息发送结果
          break;
        case 20: // 单条消息
          this.userMsg(data);
          break;
        case 40: // 建立websocket 连接
          break;
        case 50: // 账号重复登录
          break;
        case 60: // 服务器重启  掉线
          break;
        case 70: // 消息发送超时
          break;
        default:
          break;
      }
    },
    // 格式化数据
    convertMsg(data) {
      const msgData = data.record || data.result || data;
      if (typeof msgData.content === "string") {
        msgData.content = JSON.parse(msgData.content);
      }
      this.userMsg(msgData);
    },
    // 用户消息类型
    async userMsg(data) {
      // 一般消息处理 1001-文本消息, 1003-文件消息, 1004-小视频消息, 1005-位置消息，1009-音频消息，10010-图片类型消息,1012-分享用户或群名片
      const msgtype = [1001, 1003, 1004, 1005, 1009, 1010, 1012];
      if (msgtype.includes(data.msgtype)) {
        await this.converMsg(data);
        return;
      }
      // 系统公告
      if (data.msgtype === 1014) {
        if (data.content.status === 10) {
          await this.converMsg(data);
        } else if (data.content.status === 20) {
          const sysIndex = this.chatMsg.findIndex(
            v => v.content.sysnoticeid === data.content.sysnoticeid
          );
          if (~sysIndex < 0) {
            this.chatMsg.splice(sysIndex, 1);
            this.set_chatMsg(this.chatMsg);
            this.chatUsers.forEach(v => {
              if (v.id === 1) {
                const array = this.chatMsg.filter(v => v.id === 1);
                if (array.length) {
                  v.content = array[array.length - 1].content;
                } else {
                  v.content = {
                    content: ""
                  };
                }
              }
            });
            this.set_chatUsers(this.chatUsers);
          }
        }
        return;
      }
      // 在线用户
      if (data.msgtype === 2018) {
        this.set_onlineUserIds(data.content.userids);
        return;
      }
      if (data.msgtype === 2028) {
        this.friends.forEach(v => {
          if (v.id === data.fromid) {
            v.secretstatus = data.content.operator === 10 ? 20 : 10;
            v.secret = data.content.secret || "";
          }
        });
        console.log(this.friends);
        this.set_friends(this.friends);
        // clienttype: "OSS"
        // content: "{"createuser":300172472,"operator":10,"secret":"哈哈"}"
        // createtime: 1587108983859
        // encrypt: 10
        // fromid: 300172472
        // msgkind: 20
        // msgtype: 2028
        // status: 10
        // targetid: 304716630
        return;
      }
      switch (data.msgtype) {
        case 1011: // 提示消息类型
          const content = data.content;
          if (content.type === 100) {
            // clienttype: "OSS"
            // content: "{"content":"已经是好友了可以开始聊天!","type":100}"
            // createtime: 1587005642804
            // encrypt: 10
            // fromid: 300390197
            // messageid: "300390197-304716630-0k9266n1w"
            // msgkind: 20
            // msgtype: 1011
            // status: 10
            // targetid: 304716630
            // 好友同意通知
            await this.converMsg(data);
          } else if (content.type === 200) {
            // 创建群
            this.groups.push({
              grouptype: content.extra.grouptype,
              usernum: content.extra.usernum,
              name: content.extra.groupname,
              id: content.extra.groupid,
              face:
                content.extra.grouptype === 20
                  ? require("@/assets/image/icon_group.png")
                  : content.extra.groupface,
              letter: "群聊",
              msgkind: 30,
              syssetting: content.extra.syssetting // 1是开启禁言，0是关闭禁言
            });
            await this.converMsg(data);
          } else if (content.type === 201) {
            // 退出群聊
            await this.converMsg(data);
          } else if (content.type === 202) {
            // 被踢出群聊
            await this.converMsg(data);
            // clienttype: "OSS"
            // content: "{"content":"吴振被踢出了群聊!","extra":{"groupId":104708597,"targetUserIds":[304716630],"targetUserNames":["吴振"]},"type":202}"
            // createtime: 1587373689972
            // encrypt: 10
            // fromid: 304022596
            // messageid: "304022596-104708597-0k989b62c"
            // msgkind: 30
            // msgtype: 1011
            // status: 10
            // targetid: 104708597
          } else if (content.type === 204) {
            // 加入群聊
            this.groups.push({
              grouptype: content.extra.grouptype,
              usernum: content.extra.usernum,
              name: content.extra.groupname,
              id: content.extra.groupid,
              face:
                content.extra.grouptype === 20
                  ? require("@/assets/image/icon_group.png")
                  : content.extra.groupface,
              letter: "群聊",
              msgkind: 30,
              syssetting: content.extra.syssetting // 1是开启禁言，0是关闭禁言
            });
            await this.converMsg(data);
          } else if (content.type === 205) {
            // 解散群
            // 判断是否存在
            // const currentIndex = this.chatUsers.findIndex(
            //   v => v.id === data.targetid
            // );
            const currentIndex1 = this.groups.findIndex(
              v => v.id === data.targetid
            );
            // if (~currentIndex < 0) {
            //   this.chatUsers.splice(currentIndex, 1);
            // }
            if (~currentIndex1 < 0) {
              this.groups.splice(currentIndex1, 1);
            }
            console.log(111);
            // this.set_chatUsers(this.chatUsers);
            // if (this.chatting.id === data.targetid) {
            //   this.set_chatting({});
            // }
          } else if (content.type === 206) {
            //  群禁言开启关闭
            const currentIndex = this.groups.findIndex(
              v => v.id === data.targetid
            );
            if (~currentIndex < 0) {
              const currentGroup = this.groups[currentIndex];
              this.groups.splice(currentIndex, 1);
              if (data.content.extra.status === 20) {
                currentGroup["syssetting"] = 1;
              } else {
                currentGroup["syssetting"] = 0;
              }
              this.groups.unshift({ ...currentGroup });
              this.set_groups(this.groups);
            }
            await this.converMsg(data);
          } else if (content.type === 207) {
            // 更新群名称
            const currentIndex = this.groups.findIndex(
              v => v.id === data.targetid
            );
            if (~currentIndex < 0) {
              const currentGroup = this.groups[currentIndex];
              this.groups.splice(currentIndex, 1);
              this.groups.unshift({
                ...currentGroup,
                ...{
                  name: content.extra.groupname
                }
              });
              this.set_groups(this.groups);
            }
            await this.converMsg(data);
          } else if (content.type === 209) {
            // 匿名、普通群切换
            const currentIndex = this.groups.findIndex(
              v => v.id === data.targetid
            );
            if (~currentIndex < 0) {
              const currentGroup = this.groups[currentIndex];
              this.groups.splice(currentIndex, 1);
              this.groups.unshift({
                ...currentGroup,
                ...{
                  grouptype: currentGroup.grouptype === 20 ? 10 : 20
                }
              });
              this.set_groups(this.groups);
            }
            await this.converMsg(data);
          } else {
            await this.converMsg(data);
          }
          break;
        case 2004: // 已读通知消息
          this.chatUsers.forEach(v => {
            if (v.messageid === data.content.messageId) {
              v.msgStatus = 2; // 已读
            }
          });
          const chatMsg = this.chatMsg.map(v => {
            if (v.id === data.fromid && v.msgStatus === 1) {
              v["msgStatus"] = 2; // 已读
            }
            return v;
          });
          this.set_chatMsg(chatMsg);
          break;
        case 2014: // 用户上下线通知
          if (data.content.onlinestatus === 10) {
            this.onlineUserIds.splice(
              this.onlineUserIds.findIndex(v => v === data.content.userid),
              1
            );
          } else {
            this.onlineUserIds.push(data.content.userid);
          }
          break;
        case 2016: // 撤回一条消息
          const currentIndex = this.chatMsg.findIndex(
            v => v.messageid === data.content.recallmsgid
          );
          this.chatMsg.splice(currentIndex, 1, {
            ...this.chatMsg[currentIndex],
            ...data,
            ...{
              content: {
                content: this.$t("con_recall")
              },
              isRead: true
            }
          });
          this.set_chatMsg(this.chatMsg);
          const msg = this.$store.getters.getChatMsg(this.chatting.id);
          this.storeChatUsers(msg[msg.length - 1]);
          break;
        case 2017: // 撤回全部消息
          let array = [];
          if (data.msgkind === 20) {
            array = this.chatMsg.filter(v => v.id !== data.fromid);
          } else if (data.msgkind === 30) {
            const currentGroup = this.groups.find(v => v.id === data.targetid);
            if (data.fromid === currentGroup.createuserid) {
              array = this.chatMsg.filter(v => v.id !== data.targetid);
            } else {
              array = this.chatMsg.filter(
                v => v.fromid !== data.fromid && v.id === data.targetid
              );
            }
          }
          this.set_chatMsg(array);
          data.content = {
            ...data.content,
            ...{ content: "" }
          };
          await this.converMsg(data);
          break;
        case 2020: // 退出web端登录
          const res = await this.$store.dispatch("onLogout");
          if (res.success) {
            this.$imWebSocket.closeScoket();
            this.$router.replace("/");
          }
          break;
        case 2021: // 对方正在输入...
          if (this.chatting.id === data.fromid) {
            clearTimeout(this.inputTimer);
            this.chatting["status"] = data.content.status;
            this.set_chatting(this.chatting);
            this.inputTimer = setTimeout(() => {
              this.chatting["status"] = null;
              this.set_chatting(this.chatting);
            }, 3000);
          }
          break;
        case 2026: // app端同步消息
          if (data.clienttype === "WEB") return;
          const obj = {
            ...data,
            ...{
              msgtype: data.content.parentmsgtype,
              content: data.content.content,
              messageid: data.content.parentmsgid,
              id: data.targetid
            }
          };
          // app端操作一键撤回
          if (obj.msgtype === 2017) {
            obj["fromid"] = data.targetid;
            obj["targetid"] = data.fromid;
          }
          await this.userMsg(obj);
          break;
        default:
          break;
      }
    },
    // 处理发送返回消息
    async convertResponseMsg(data) {
      const content = JSON.parse(data.content);
      const http_seqno = data.http_seqno;
      let msgStatus = 1;
      // 未登录，退出登录
      if (content.retcode === 30020001 && content.retcode === 30010001) {
        await this.$store.dispatch("onClearStroage");
        Message.error(content.retinfo);
        this.$imWebSocket.closeScoket();
        setTimeout(() => {
          this.$router.replace("/");
        }, 1000);
        return;
      }
      if (
        content.retcode === 30040003 ||
        content.retcode === 30040011 ||
        content.retcode === 30040009
      ) {
        // 30040003好友用户不存在;30040011被拉黑;30040009用户不在群组中
        if (this.input_httpSeqno === Number(http_seqno)) return;
        Message.error(content.retinfo);
        msgStatus = -1;
      }
      if (content.success) {
        const msgtype = content.result.msgtype;
        if (
          msgtype === 2021 ||
          msgtype === 2004 ||
          msgtype === 2017 ||
          msgtype === 2016
        )
          return;
        msgStatus = 1;
      }
      const currentMsg = this.chatMsg.find(
        v => v.createtime && Number(v.createtime) === Number(http_seqno)
      );
      this.storeChatUsers({
        ...currentMsg,
        ...{
          msgStatus: msgStatus
        }
      });
      const chatMsg = this.chatMsg.map(v => {
        if (v.createtime && Number(v.createtime) === Number(http_seqno)) {
          v["msgStatus"] = msgStatus; // 已发送
        }
        return v;
      });
      this.set_chatMsg(chatMsg);
    },
    // 消息处理
    async converMsg(data) {
      this.chatting["status"] = null;
      this.set_chatting(this.chatting);
      clearTimeout(this.inputTimer);
      let user = {};
      if (data.msgkind === 20) {
        // 单聊
        await this.checkUser(data);
        user = this.friends.find(m => m.id === data.fromid);
      } else if (data.msgkind === 30) {
        // 群聊
        await this.checkGroupUser(data);
        const groupMember = this.groups.find(m => m.id === data.targetid)
          .groupMember;
        const obj = groupMember.find(m => m.userid === data.fromid);
        groupMember.find(m => m.userid === data.fromid);
        user = {
          annoyindex: obj.annoyindex || 0,
          name: obj.usernickname || obj.username,
          id: data.targetid,
          face: obj.face
        };
      } else if (data.msgkind === 10) {
        user = {
          id: data.fromid
        };
      }
      const obj = {
        ...data,
        ...{
          name: user.name,
          id: data.id || user.id,
          face: user.face,
          annoyindex: user.annoyindex || 0,
          msgStatus: 1,
          isPlay: false,
          isRead: data.fromid === this.userInfo.userid
        }
      };
      console.log(obj);
      this.storeChatUsers(obj);
      this.chatMsg.push(obj);
      this.set_chatMsg(this.chatMsg);
    },
    // 检查单聊用户信息
    async checkUser(data) {
      const user = this.friends.find(m => m.id === data.fromid);
      if (!user) {
        await this.getUserInfoData(data.fromid);
      }
    },
    // 检查群聊用户信息
    async checkGroupUser(data) {
      const groupMember = this.groups.find(m => m.id === data.targetid)
        .groupMember;
      if (!groupMember) {
        await this.getGroupMemberData(data.targetid);
      } else {
        const user = groupMember.find(m => m.userid === data.fromid);
        if (!user) {
          await this.getGroupMemberData(data.targetid);
        }
      }
    }
  }
};
